package com.comment.util.name;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

public class NameGenerator {
    private static final String FIRST_NAME_LIBRARY;
    private static final String LAST_NAME_LIBRARY;

    private static final List<String> FIRST_NAMES = new ArrayList<>();
    private static final List<String> LAST_NAMES = new ArrayList<>();
    private static final Random random = new Random();

    static {
        FIRST_NAME_LIBRARY = "/name/first.txt";
        LAST_NAME_LIBRARY = "/name/last.txt";
        loadNames();
    }

    private static void loadNames() {
        try (
                InputStream firstNameStream = Objects.requireNonNull(NameGenerator.class.getResource(FIRST_NAME_LIBRARY)).openStream();
                InputStream lastNameStream = Objects.requireNonNull(NameGenerator.class.getResource(LAST_NAME_LIBRARY)).openStream();
        ) {

            if (firstNameStream == null || lastNameStream == null) {
                throw new RuntimeException("Failed to find name library files in classpath");
            }

            BufferedReader firstNameReader = new BufferedReader(new InputStreamReader(firstNameStream));
            BufferedReader lastNameReader = new BufferedReader(new InputStreamReader(lastNameStream));

            String line;
            while ((line = firstNameReader.readLine()) != null) {
                FIRST_NAMES.add(line);
            }
            while ((line = lastNameReader.readLine()) != null) {
                LAST_NAMES.add(line);
            }
        } catch (IOException e) {
            throw new RuntimeException("未能加载名字库", e);
        }
    }

    public static String generateName() {
        String firstName = FIRST_NAMES.get(random.nextInt(FIRST_NAMES.size()));
        String lastName = LAST_NAMES.get(random.nextInt(LAST_NAMES.size()));
        return firstName + lastName;
    }
}
